<?php

declare(strict_types=1);

namespace app\model\develop;

use owns\interface\OwnsModelInteface;

class DistrictModel extends OwnsModelInteface
{
    protected $name = 'develop_district';

    protected $createTime = false;

    protected $updateTime = false;

    protected $field = [];

    /**
     * 查询条件
     * @param object $query
     * @param array $param
     */
    public function scopeCustom(object $query, array $param)
    {
        //上级ID
        if ($id = $param['id'] ?? '') {
            $query->where('id', $id);
        }
        //状态：0禁用 1启用
        $status = $param['status'] ?? '';
        if (is_numeric($status)) {
            $query->where('status', $status);
        }
        //上级ID
        $parentId = $param['parent_id'] ?? '';
        if (is_numeric($parentId)) {
            $query->where('parent_id', $parentId);
        }
        //地名
        if ($name = $param['name'] ?? '') {
            $query->whereLike('name', '%' . trim($name) . '%');
        }
        //省份
        if ($province = $param['province'] ?? '') {
            $query->whereLike('province', '%' . trim($province) . '%');
        }
        //城市
        if ($city = $param['city'] ?? '') {
            $query->whereLike('city', '%' . trim($city) . '%');
        }
        //区/县
        if ($district = $param['district'] ?? '') {
            $query->whereLike('district', '%' . trim($district) . '%');
        }
        //乡/镇
        if ($town = $param['town'] ?? '') {
            $query->whereLike('town', '%' . trim($town) . '%');
        }
        //简称
        if ($shortname = $param['shortname'] ?? '') {
            $query->whereLike('shortname', '%' . trim($shortname) . '%');
        }
        //区域选项
        if ($townId = $param['town_id'] ?? 0) {
            $query->where('id', $townId);
        } else if ($districtId = $param['district_id'] ?? 0) {
            if (DistrictModel::where('parent_id', $districtId)->find()) {
                $query->where('parent_id', $districtId);
            } else {
                $query->where('id', $districtId);
            }
        } else if ($cityId = $param['city_id'] ?? 0) {
            $query->where('parent_id', $cityId);
        } else if ($provinceId = $param['province_id'] ?? 0) {
            $query->where('parent_id', $provinceId);
        }
    }
}
